function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date,deadline=0) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()+deadline

  const hour = date.getHours()
  const minute = date.getMinutes()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function previewImage(current,urls){
  wx.previewImage({
    current: current, // 当前显示图片的http链接
    urls: urls, // 需要预览的图片http链接列表
    fail:err=>{console.log(err)}
  })
}

export function navigateTo(url){
  wx.navigateTo({
    url:url,
    fail(err){
      console.log(err)
    }
  })
}


export function redirectTo(url){
  console.log(url)
  wx.redirectTo({
    url:url,
    fail:err=>{
      console.log(err)
    }
  })
}

export function switchTab(url){
  console.log(url)
  wx.switchTab({
    url:url,
    fail:err=>{
      console.log(err)
    }
  })
}

export function sexTag(value){
  if(value=="男"){
    return 1
  }else if(value=="女"){
    return 2
  }else{
    return 0
  }
}

export function sexTag1(value){
  if(value==1){
    return '男'
  }else if(value==2){
    return '女'
  }else{
    return '男女不限'
  }
}

export function showToast(title,icon="none",time=1500){
  wx.showToast({
    title:title,
    icon:icon,
    duration:time=="" ? 1500 :time
  })
}

export function showModal(title,content){
  var _this=this
  let promise=new Promise((resolve ,reject) => {
    wx.showModal({
      title: title,
      content: content,
      success (res) {
        if (res.confirm) {
          resolve(true)
        } else if (res.cancel) {
           resolve(false)
        }
      },
      fail:err=>{
        reject(err)
      }
    })
  })
  return promise
}

//本地选取一张图片上传
export function upLoadImage(url){
  var _this=this
  let promise=new Promise((resolve ,reject) => {
    
    wx.chooseImage({
    count:1,
    sizeType: ['original'],
    success(res){
      wx.showLoading({
        title:'上传中',
        mask:true
      })
      wx.uploadFile({
        url:"https://www.gangerp.com/api/file/upload-img",
        filePath:res.tempFilePaths[0],
        name:"photo",
        header: {
        'content-type': 'application/json' // 默认值
        },
        success:data=>{
          resolve(data)
          wx.hideLoading()
        },
        fail:err=>{
          reject(err)
          wx.hideLoading()
        }
      })
    }
   })
  })
  return promise
}
export const mixin2={
  methods:{
    upLoadImage(url){
      let _this=this
      let promise=new Promise((resolve ,reject) => {
        wx.chooseImage({
        count:1,
        success(res){
          if(_this.logoImg){
            _this.logoImg.push({src:'https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/recruit/icon/loading.gif'})//显示loading图片
          }
          wx.uploadFile({
            url:"https://wx.zhaowea.com/api/file/upload-image",
            filePath:res.tempFilePaths[0],
            name:"photo",
            header: {
            'content-type': 'application/json' // 默认值
            },
            success:data=>{
              if(_this.logoImg){
                _this.logoImg.pop()
              }
              resolve(data)
            },
            fail:err=>{
              reject(err)
            }
          })
        }
       })
      })
      return promise
    }
  }
}
export const mixin1={
  data(){return{
      province:'',
      cityList:'',
      countyList:'',
      multiArray3: [[], [], []],
      multiIndex3: [0,0,0],
  }},
  methods:{
    bindMultiPickerColumnChange(e){

      let val=e.target.value;
      switch (e.target.column) {
        case 0:
        let arr=this.getArr(this.province[val],this.cityList)
          this.$set(this.multiArray3,1,[])
          this.$set(this.multiArray3,1,arr);//设置第二组数据
          let arr2=this.getArr(arr[0],this.countyList);
          if(arr2){
            this.$set(this.multiArray3,2,arr2);//设置第三组数据
          }else{
            this.$set(this.multiArray3,2,['-']);
          }
          this.$set(this.multiIndex3,0,val);//设置当前显示的下标
          this.$set(this.multiIndex3,1,0);
          this.$set(this.multiIndex3,2,0);
          break;
        case 1:
        let arr3=this.getArr(this.multiArray3[1][val],this.countyList);
        this.$set(this.multiArray3,2,[])
          if(arr3){
            this.$set(this.multiArray3,2,arr3)
          }else{
            this.$set(this.multiArray3,2,['-']);
          } 
          this.$set(this.multiIndex3,1,val)
          this.$set(this.multiIndex3,2,0);
          break;
      }
      },
      getArr(address,arr){
        for(let p in arr){
          if(address==p){
            return arr[p]
          }
        }
      },
      async getAddress(url='/other/get-address-all'){//获取传入的数据
        let res=await this.$request.getData(url);
        this.initAddress=res
        let province=[];
        let cityList={};//{'广东省':['广州市'，'深圳市']}放某省内的市
        let countyList={};//{'广州市':['番禺区'，'增城区']}放某区市的区
        if(res.data.level=='success'){//获取自主传入的地址
          res.data.data.forEach((val)=>{
            if(val.name!=''){
              province.push(val.name);
              if(val.cityList!=''){
                let arr=[];
                val.cityList.forEach(val1=>{
                  arr.push(val1.name);
                  if(val1.areaList!=''){
                    let arr2=[]
                    val1.areaList.forEach(val2=>{
                      arr2.push(val2.name)
                    })
                    countyList[val1.name]=arr2
                  }
                })
                cityList[val.name]=arr;
              }
            }
          })
        }
        this.province=province;
        // console.log(province,11111)
        this.cityList=cityList;
        this.countyList=countyList;
        this.multiArray3[0]=this.province
        this.multiArray3[1]=this.getArr(this.province[0],this.cityList);
        this.multiArray3[2]=this.getArr(this.multiArray3[1][0],this.countyList);
      }
  },
  mounted() {
    // this.getAddress()
  },
}

export  /**
* 检测当前的小程序
* 是否是最新版本，是否需要下载、更新
*/
function checkUpdateVersion() {
 //判断微信版本是否 兼容小程序更新机制API的使用
 if (wx.canIUse('getUpdateManager')) {
   //创建 UpdateManager 实例
   const updateManager = wx.getUpdateManager();
   //检测版本更新
   updateManager.onCheckForUpdate(function(res) {
     // 请求完新版本信息的回调
     if (res.hasUpdate) {
       //监听小程序有版本更新事件
       updateManager.onUpdateReady(function() {
         //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
        //  updateManager.applyUpdate();

        wx.showModal({
            title: "更新提示",
            content: "新版本已经准备好，是否重启应用？",
            success: function (res) {
                if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate();
                }
            }
        });
       })
       updateManager.onUpdateFailed(function() {
         // 新版本下载失败
         wx.showModal({
           title: '已经有新版本喽~',
           content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
         })
       })
     }
   })
 } else {
   //TODO 此时微信版本太低（一般而言版本都是支持的）
   wx.showModal({
     title: '溫馨提示',
     content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
   })
 }
}

export function share(res,title,path){
  return {
    title:title,
    path:path,
    success(res){
      wx.showToast({
        title:"转发成功",
      })
    },
    fail(err){
      console.log(err)
    }
  }
}

//写cookies 
export function setCookie(name,value){ 
  var Days = 30; 
  var exp = new Date(); 
  exp.setTime(exp.getTime() + Days*24*60*60*1000); 
  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 

//读取cookies 
export function getCookie(name){ 
  var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
    return unescape(arr[2]); 
  else 
    return null; 
} 
//删除cookies 
export function delCookie(name) { 
    var exp = new Date(); 
    exp.setTime(exp.getTime() - 1); 
    var cval=getCookie(name); 
    if(cval!=null){
      document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
}

//获取URL参数
function getQueryVariable(variable){
  var url = window.location.href.split("?");
  if(url[1] == '' || url[1] == undefined){
    return (false)
  }
  var vars = url[1].split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return (false)
}

export default {
  formatNumber,
  formatTime,
  navigateTo,
  showToast,
  redirectTo,
  upLoadImage,
  previewImage,
  switchTab,
  sexTag,
  sexTag1,
  showModal,
  mixin1,
  mixin2,
  checkUpdateVersion,
  share,
  setCookie,
  getCookie,
  delCookie,
  getQueryVariable
}
